package org.example.cloud.payment.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.example.cloud.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 测试线程池隔离和信号量隔离
 *
 * 1.线程池隔离
 *   a.线程池隔离，是异步，资源上宽裕，但是资源耗费比较大
 *   b.线程池隔离，无法获取主线程数据
 *
 * 2.信号量隔离
 *   a.信号量隔离是同步，直接使用tomcat,也就是主线程来执行，不会进行资源隔离
 *   b.信号量隔离，可以获取到主线程数据
 */
@RestController
@RequestMapping("/payment4")
public class PaymentController4 {

    @Autowired
    private PaymentService paymentService;


    @HystrixCommand(fallbackMethod ="handle")
    @GetMapping("/hytrix-dashboard41/ok")
    public String hytrixDashboard1(){
        System.out.println("执行开始--hytrixDashboard1");
        System.out.println(Thread.currentThread().getName()+"--hytrixDashboard1");
        System.out.println("执行结束--hytrixDashboard1");
        return "ok";
    }


    /**
     * execution.isolation.strategy 配置隔离策略，默认使用线程池方式，可以改成信号量
     * @return
     */
    @HystrixCommand(
            fallbackMethod ="handle",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE"),
                            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "20000"),
                    @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
                    @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests",value ="1")}
    )
    @GetMapping("/hytrix-dashboard42/ok")
    public String hytrixDashboard2(){
        System.out.println("执行开始--hytrixDashboard2");
        int i=10/0;  //演示发生异常
        System.out.println(Thread.currentThread().getName()+"--hytrixDashboard2");
        System.out.println("执行结束--hytrixDashboard2");
        return "ok";
    }


    private void sleep(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            //e.printStackTrace();
        }
    }

    private String handle(){
        System.out.println(Thread.currentThread().getName()+"--访问错误"+new Date());
        return "error";
    }

}
